package com.frame.system.controller;

import com.frame.common.core.entity.SysMenu;
import com.frame.common.core.security.entity.SecurityUser;
import com.frame.common.core.security.utils.SecurityUtils;
import com.frame.common.core.security.utils.TokenUtil;
import com.frame.security.service.ISysMenuService;
import com.frame.stant.constans.Constants;
import com.frame.stant.constans.UserConstants;
import com.frame.stant.utils.R;
import com.frame.stant.utils.ServletUtils;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 菜单信息
 *
 * @author ruoyi
 */
@Api(tags = "菜单")
@RestController
@RequestMapping("/system/menu")
@AllArgsConstructor
public class SysMenuController  {

    private final ISysMenuService menuService;
    private final TokenUtil tokenUtil;

    /**
     * 获取菜单列表
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:menu:list')")
    @GetMapping("/list")
    public R list(SysMenu menu) {
        SecurityUser loginUser = tokenUtil.getCurrentUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return R.success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:menu:query')")
    @GetMapping(value = "/{menuId}")
    public R getInfo(@PathVariable Long menuId) {
        return R.success(menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public R treeSelect(SysMenu menu) {
        SecurityUser loginUser = tokenUtil.getCurrentUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return R.success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public R roleMenuTreeSelect(@PathVariable("roleId") Long roleId) {
        SecurityUser loginUser = tokenUtil.getCurrentUser(ServletUtils.getRequest());
        List<SysMenu> menus = menuService.selectMenuList(loginUser.getUser().getUserId());
        R result = R.success();
        Map map = Maps.newHashMap();
        map.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        map.put("menus", menuService.buildMenuTreeSelect(menus));
        result.setData(map);
        return result;
    }

    /**
     * 新增菜单
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:menu:add')")
//    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return R.error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
            return R.error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(SecurityUtils.getUsername());
        return R.success(menuService.save(menu));
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:menu:edit')")
//    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return R.error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
            return R.error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return R.error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return R.success(menuService.updateById(menu));
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@custom.hasAnyAuthority('system:menu:remove')")
//    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public R remove(@PathVariable("menuId") Long menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return R.error("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return R.error("菜单已分配,不允许删除");
        }
        return R.success(menuService.removeById(menuId));
    }
}